/*
 * This file is part of the <a href="http://code.google.com/p/pux">PUX Framework</a>
 *
 * Copyright 2008 by <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package de.teamskill.pux.library.util;

import java.util.Collection;
import java.util.Iterator;

import de.teamskill.pux.engine.ConfigurationPort;
import de.teamskill.pux.engine.DataElement;
import de.teamskill.pux.engine.InputPort;
import de.teamskill.pux.engine.AbstractNode;
import de.teamskill.pux.engine.OutputPort;

/**
 * CollectionFilterNode - removes all objects from an incoming Collections which
 * are not of a given class type
 * 
 * @author <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 * 
 */
public class CollectionFilterNode extends AbstractNode {

	/**
	 * IN_COLLECTION
	 */
	public static final String IN_COLLECTION = "COLLECTION";

	/**
	 * IN_TYPE
	 */
	private static final String IN_TYPE = "classType";

	/**
	 * OUT_COLLECTION
	 */
	private static final String OUT_COLLECTION = "COLLECTION";

	/**
	 * in
	 */
	private InputPort in;

	/**
	 * type
	 */
	private InputPort type;

	/**
	 * out
	 */
	private OutputPort out;

	/**
	 * CollectionFilterNode Constructor
	 * 
	 */
	public CollectionFilterNode() {
		this("CFILTER" + nr++, false);
	}

	/**
	 * CollectionFilterNode Constructor
	 * 
	 * @param nodeName
	 * @param continuous
	 */
	public CollectionFilterNode(String nodeName, boolean continuous) {
		super(nodeName, continuous);
	}

	/**
	 * @see de.teamskill.pux.engine.AbstractNode#compute()
	 */
	@SuppressWarnings("unchecked")
	public void compute() {
		Collection<Object> c = (Collection<Object>) in.fetchData();
		Class<?> t = (Class<?>) type.fetchData();
		int removed = 0;
		for (Iterator<Object> it = c.iterator(); it.hasNext();) {
			Object o = it.next();
			if (!t.isAssignableFrom(o.getClass())) {
				it.remove();
				removed++;
			}
		}
		DataElement de = new DataElement(c);
		de.annotate("itemsRemoved", "" + removed);
		out.pushBuffer(de);
	}

	/**
	 * @see de.teamskill.pux.engine.AbstractNode#createPorts()
	 */
	protected void createPorts() {
		in = addInputPort(IN_COLLECTION, Collection.class, true);
		type = addConfigurationPort(new ConfigurationPort(IN_TYPE, this, true, Class.class, Object.class));
		out = addOutputPort(new OutputPort(OUT_COLLECTION, this, Collection.class));
	}

}
